package com.wut.clock.service.impl;

import com.wut.clock.common.exception.Asserts;
import com.wut.clock.common.util.RedisKeyUtil;
import com.wut.clock.mapper.ArticleMapper;
import com.wut.clock.service.IHomeService;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author ZYH
 * @unit D9Lab
 * @description 首页实现类
 * @date 2022/6/2 10:02
 */
@Service
@RequiredArgsConstructor
@SuppressWarnings("unchecked")
public class HomeServiceImpl implements IHomeService {

    private final RedisTemplate redisTemplate;

    private final ArticleMapper articleMapper;

    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void recordUV(String ip) {
        String redisKey = RedisKeyUtil.getUVKey(df.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(redisKey,ip);
    }

    @Override
    public Long calculateUV(Date startDate, Date endDate) {
        if(startDate == null || endDate == null) Asserts.fail("开始时间或结束时间不能为空！");
        // 整理该日期范围内的key
        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while (!calendar.getTime().after(endDate)){
            String key = RedisKeyUtil.getUVKey(df.format(calendar.getTime()));
            keyList.add(key);
            calendar.add(Calendar.DATE,1);
        }
        // 合并这些数据
        String redisKey = RedisKeyUtil.getUVKey(df.format(startDate), df.format(endDate));
        return redisTemplate.opsForHyperLogLog().size(redisKey);
    }

    @Override
    public void recordDAU(Integer userId) {
        String redisKey = RedisKeyUtil.getDAUKey(df.format(new Date()));
        redisTemplate.opsForValue().setBit(redisKey,userId,true);
    }

    @Override
    public Long calculateDAU(Date startDate, Date endDate) {
        if(startDate == null || endDate == null) Asserts.fail("开始时间或结束时间不能为空！");
        // 整理该日期范围内的key
        List<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while (!calendar.getTime().after(endDate)){
            String key = RedisKeyUtil.getDAUKey(df.format(calendar.getTime()));
            keyList.add(key.getBytes());
            calendar.add(Calendar.DATE,1);
        }
        // 合并这些数据,进行or运算
        return (Long) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                String redisKey = RedisKeyUtil.getDAUKey(df.format(startDate), df.format(endDate));
                connection.bitOp(RedisStringCommands.BitOperation.OR,redisKey.getBytes(),keyList.toArray(new byte[0][0]));
                return connection.bitCount(redisKey.getBytes());
            }
        });
    }

    @Override
    public Long getArticleCount(Date startDate, Date endDate) {
        return articleMapper.getArticleCount(startDate,endDate);
    }
}
